//
//  OptionalUtils.swift
//
//  Created by Ink on 2024/9/20.
//  Copyright © 2024 ZM. All rights reserved.
//

import Foundation

// MARK: 递归解析 wrapped
public func deepUnwrap(_ any: Any) -> Any? {
    if let optional = any as? _OptionalProtocol {
        return optional._deepUnwrapped
    }
    return any
}

public protocol _OptionalProtocol {
    var _deepUnwrapped: Any? { get }
}
 
extension Optional: _OptionalProtocol {
    public var _deepUnwrapped: Any? {
        if let wrapped = self { return deepUnwrap(wrapped) }
        return nil
    }
}


public extension Optional {
    /// 判断 Optional 值是否为空（支持空字符串、空集合、空字典等）
    var isEmpty: Bool {
        guard let value = self else {
            return true // 如果为 nil，则为空
        }
        
        switch value {
        case is NSNull:
            return true // NSNull 为空
        case let string as String:
            return string.isEmpty // 空字符串
        case let array as [Any]:
            return array.isEmpty // 空数组
        case let dictionary as [AnyHashable: Any]:
            return dictionary.isEmpty // 空字典
        case let set as Set<AnyHashable>:
            return set.isEmpty // 空集合
        default:
            return false // 其他类型非空
        }
    }
    
    /// 可选值为空的时候返回 true
    var isNone: Bool {
        switch self {
        case .some( _ ):
            return false
        case .none:
            return true
        }
    }

    /// 返回可选值或 `else` 表达式返回的值
    /// eg. optional.or(else: Selector)
    func or(else: @autoclosure () -> Wrapped) -> Wrapped {
        return self ?? `else`()
    }

    /// 返回可选值或者 `else` 闭包返回的值
    /// 例如. optional.or(else: {
    /// ... do a lot of stuff
    /// })
    func or(else: () -> Wrapped) -> Wrapped {
        return self ?? `else`()
    }

    /// 可选值不为空且可选值满足 `predicate` 条件才返回，否则返回 `nil`
    func filter(_ predicate: (Wrapped) -> Bool) -> Wrapped? {
        guard let unwrapped = self,
            predicate(unwrapped) else { return nil }
        return unwrapped
    }
}
